package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.xml.transform.Result;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO placeAnOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //判断业务异常
        //判断地址栏是否为空
        AddressBook byId = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (byId == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        ShoppingCart shoppingCart = new ShoppingCart();
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shoppingCartMapper.queryByUserId(shoppingCart);
        if (list == null && list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表添加数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PAID);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(currentId);
        orders.setAddressBookId(byId.getId());
        orders.setPhone(byId.getPhone());
        orders.setAddress(byId.getDetail());
        orders.setConsignee(byId.getConsignee());

        orderMapper.insert(orders);

        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        //向订单明细表添加n条数据
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailMapper.insertList(orderDetails);

        //清空当前用户的购物车
        shoppingCartMapper.deleteAll(currentId);

//        自己写的
//        OrderSubmitVO orderSubmitVO = orderMapper.queryUserId(currentId);
        //老师写的
        OrderSubmitVO submitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return submitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }


    /**
     * 分页查询历史下单
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO pageQueryDTO) {
        Long currentId = BaseContext.getCurrentId();
        pageQueryDTO.setUserId(currentId);
        pageQueryDTO.setStatus(StatusConstant.ENABLE);
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<OrderVO> orderVOS = orderMapper.historyOrders(pageQueryDTO);
        log.info("orderVOS:{}", orderVOS);
        System.out.println(orderVOS);
        return new PageResult(orderVOS.getTotal(), orderVOS.getResult());
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {

        //查出订单明细表
        OrderDetail orderDetail = orderDetailMapper.getByOrderId(id);

        Long userId = BaseContext.getCurrentId();

        //再将已付过的商品明细加入到购物车中
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .name(orderDetail.getName())
                .userId(userId)
                .dishId(orderDetail.getDishId())
                .setmealId(orderDetail.getSetmealId())
                .dishFlavor(orderDetail.getDishFlavor())
                .number(orderDetail.getNumber())
                .amount(orderDetail.getAmount())
                .image(orderDetail.getImage())
                .createTime(LocalDateTime.now())
                .build();

        //将数据插入
        shoppingCartMapper.add(shoppingCart);
    }

    /**
     * 没有商家好所以自己添加数据返回回给微信上面是微信支付的正确流程
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO mockPayment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        orderPaymentVO.setNonceStr(UUID.randomUUID().toString());
        orderPaymentVO.setPaySign("要相信光");
        orderPaymentVO.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        int i = 0;
        i++;
        orderPaymentVO.setSignType(Integer.toString(i));
        orderPaymentVO.setPackageStr(Integer.toString(i));

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1); //1表示来单提醒,2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + ordersPaymentDTO.getOrderNumber());

        //将map转为JSON格式
        String json = JSON.toJSONString(map);

        //调用webSocketServer的sendToAllClient方法将json推送给客户段
        webSocketServer.sendToAllClient(json);


        return orderPaymentVO;
    }

    /**
     * 管理端
     * 根据id查订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orderVOPage = orderMapper.conditionSearch(ordersPageQueryDTO);
        return new PageResult(orderVOPage.getTotal(), orderVOPage.getResult());
    }

    /**
     * 客户端
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        //根据id查找
        OrderVO orderVO = orderMapper.details(id);
        return orderVO;
    }

    /**
     * 客户端
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.rejection(ordersRejectionDTO);
    }

    /**
     * 管理端
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 管理端
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer status = orderMapper.queryStatus(Orders.TO_BE_CONFIRMED);
        orderStatisticsVO.setToBeConfirmed(status);

        status = orderMapper.queryStatus(Orders.CONFIRMED);
        orderStatisticsVO.setConfirmed(status);

        status = orderMapper.queryStatus(Orders.DELIVERY_IN_PROGRESS);
        orderStatisticsVO.setDeliveryInProgress(status);

        return orderStatisticsVO;
    }

    /**
     * 管理端
     * 取消订单
     * @param ordersCancelDTO
     */
        @Override
        public void cancel(OrdersCancelDTO ordersCancelDTO) {

        orderMapper.cancel(ordersCancelDTO);

        //修改状态
        OrdersConfirmDTO ordersConfirmDTO = new OrdersConfirmDTO();
        ordersConfirmDTO.setId(ordersCancelDTO.getId());
        ordersConfirmDTO.setStatus(Orders.CANCELLED);
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 管理端
     * 派送中
     * @param ordersConfirmDTO
     */
    @Override
    public void delivery(OrdersConfirmDTO ordersConfirmDTO) {
        ordersConfirmDTO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 完成订单
     * @param ordersConfirmDTO
     */
    @Override
    public void finish(OrdersConfirmDTO ordersConfirmDTO) {
        ordersConfirmDTO.setStatus(Orders.COMPLETED);
        //调用订单状态变化
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminders(Long id) {

        Orders orders = orderMapper.ById(id);

        //校验订单是否存在
        if (orders == null){
            throw new MissingFormatArgumentException(MessageConstant.ORDER_NOT_FOUND);
        }

        //通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号" + orders.getNumber());

        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);
    }
}
